package carl.IOIO_car;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;

// ----------------------------------------------------------------------

public class Android_Activity extends Activity 
{   	
	Main_thread simulator;
	ToggleButton togglebutton;
	EditText ip_text;
    SensorManager sm = null;
    SurfaceView view;
    Sensors_thread the_sensors=null;
    String IP_address;
	Android_Activity the_app;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		view = new SurfaceView(this);		
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		ip_text = (EditText) findViewById(R.id.IP_edit_txt);
		togglebutton = (ToggleButton) findViewById(R.id.CameraButton);
		togglebutton.setOnClickListener(new btn_listener());		
		the_app = this;
	}
	
	@Override
	protected void onResume() 
	{
		super.onResume();
	}

	protected void onStop()
	{
		super.onStop();
		simulator.stop_simu();
		this.finish();
	}
	
	private class btn_listener implements OnClickListener 
	{
	    public void onClick(View v) 
	    {		
	        // Perform action on clicks
	        if (togglebutton.isChecked()) 
	        {
	    		IP_address = ip_text.getText().toString(); 
	    		
	            simulator = new Main_thread(the_app, view, sm, IP_address);
	            the_sensors = simulator.the_sensors;	
	            sm.registerListener(the_sensors, 
	                    SensorManager.SENSOR_ORIENTATION |SensorManager.SENSOR_ACCELEROMETER,
	                    SensorManager.SENSOR_DELAY_UI);
	                        
	            simulator.start();
	        	
	            Toast.makeText(Android_Activity.this, "Start streaming", Toast.LENGTH_SHORT).show();
	        } else 
	        {
	        	simulator.stop_simu();
	            sm.unregisterListener(the_sensors);
	            Toast.makeText(Android_Activity.this, "Stop streaming", Toast.LENGTH_SHORT).show();
	        }
	    }
	}
}

